﻿using Jst.IRepository.Repositories;
using SqlSugar;

namespace Jst.Repository.SqlSugar.UnitOfWork
{
    public sealed class SugarUnitOfWork : IUnitOfWork
    {
        private readonly ISqlSugarClient _db;
        public SugarUnitOfWork(ISqlSugarClient db) => _db = db;

        public void BeginTransaction() => _db.Ado.BeginTran();

        public async Task<int> SaveChangesAsync(CancellationToken ct = default)
        {
            if (_db.Ado.Transaction == null)
                throw new InvalidOperationException("Call BeginTransaction before SaveChanges.");

            _db.Ado.CommitTran();
            return 1;
        }

        public void Rollback()
        {
            if (_db.Ado.Transaction != null)
                _db.Ado.RollbackTran();
        }

        public void Dispose()
        {
            Rollback(); // 保险起见
            (_db as IDisposable)?.Dispose();
        }
    }
}
    
